package com.lang.downloader.http.header;

import com.lang.exception.ReflectException;
import okhttp3.Headers;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class HttpResponseHeaderKeySet {

    public void headers(Headers headers) {
        Map<String, Method> headerMap = new HashMap<>();
        Class<? extends HttpResponseHeaderKeySet> type = this.getClass();
        Field[] declaredFields = type.getDeclaredFields();
        if (declaredFields.length > 0) {
            for (Field field : declaredFields) {
                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers)
                        && !Modifier.isFinal(modifiers)
                        && Modifier.isPrivate(modifiers)
                        && field.isAnnotationPresent(HttpHeader.class)) {
                    HttpHeader httpHeader = field.getAnnotation(HttpHeader.class);
                    String setterName = "set" + StringUtils.capitalize(field.getName());
                    String headerName = httpHeader.name();
                    Method setterMethod;
                    try {
                        setterMethod = type.getMethod(setterName, String.class);
                    } catch (Exception e) {
                        throw new ReflectException(e);
                    }
                    headerMap.put(StringUtils.upperCase(StringUtils.trim(headerName)), setterMethod);
                }
            }
        }
        HttpResponseHeaderKeySet httpResponseHeaderKeySet = this;
        if (headers != null && headers.size() > 0) {
            headers.forEach(header -> {
                String key = StringUtils.upperCase(StringUtils.trim(header.getFirst()));
                String value = header.getSecond();
                if (headerMap.containsKey(key)) {
                    try {
                        headerMap.get(key).invoke(httpResponseHeaderKeySet, value);
                    } catch (Exception e) {
                        throw new ReflectException(e);
                    }
                }
            });
        }
    }

}
